import { defineStore } from "pinia";

// 命名规范：use****
export const useCounterStore = defineStore("counter", {
  state: () => {
    return {
      name: "张三",
      age: 16,
    };
  },
  getters: {
    getAge: (state) => {
      return { age: state.age };
    },
    getFullInfo: (state) => {
      return { name: state.name, age: state.age };
    },
  },
  actions: {
    updateUserInfo(name: string, age: number) {
      this.name = name;
      this.age = age;
    },
    // 异步action
    async setName(name: string) {
      const res = await nameChange(name);
      return res;
    },
    // 相互调用action
    setAllInfo(name: string, age: number) {
      this.setName(name).then((res) => {
        this.name = res as string;
        this.age = age;
      });
    },
  },
});

const nameChange = (name: String) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(name + "处理完成");
    }, 2000);
  });
};
